package com.cskaoyan.market.service.admin.impl;

import com.cskaoyan.market.db.domain.MarketTopic;
import com.cskaoyan.market.db.domain.MarketTopicExample;
import com.cskaoyan.market.db.mapper.MarketTopicMapper;
import com.cskaoyan.market.service.admin.MarketTopicService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MarketTopicServiceImpl implements MarketTopicService {
    @Autowired
    MarketTopicMapper topicMapper;

    @Override
    public List<MarketTopic> list(Integer page, Integer limit, String sort, String order, String title, String subTitle) {

        // 获取example
        MarketTopicExample marketTopicExample = new MarketTopicExample();
        // 获取criteria
        MarketTopicExample.Criteria criteria = marketTopicExample.createCriteria();
        // 设置条件        
        // 排除已经被逻辑删除的
        criteria.andDeletedEqualTo(false);
        // 模糊查询
        if (!StringUtils.isEmpty(title)) {
            criteria.andTitleLike("%" + title + "%");
        }
        if (!StringUtils.isEmpty(subTitle)) {
            criteria.andSubtitleLike("%" + subTitle + "%");
        }
     
        marketTopicExample.orderBy(sort + " " + order);
        PageHelper.startPage(page, limit);
        List<MarketTopic> marketTopics = topicMapper.selectByExampleSelective(marketTopicExample);

        return marketTopics;
    }

    @Override
    public int create(MarketTopic marketTopic) {

        // 插入数据
        int resCode = topicMapper.insertSelective(marketTopic);

        return resCode;
    }

    @Override
    public int update(MarketTopic marketTopic) {

        //更新数据
        int resCode = topicMapper.updateByPrimaryKeySelective(marketTopic);

        return resCode;
    }

    @Override
    public int delete(MarketTopic marketTopic) {
        marketTopic.setDeleted(true);
        //删除数据
        int resCode = topicMapper.updateByPrimaryKeySelective(marketTopic);

        return resCode;
    }

    @Override
    public Map<String, Object> getRead(Integer id) {
        Map<String,Object> result = new HashMap<>();

        MarketTopic topic = topicMapper.selectByPrimaryKey(id);
        Integer[] goods = topic.getGoods();
        List<Integer> goodsList = Arrays.asList(goods);
        result.put("goodsList", goodsList);
        result.put("topic", topic);

        return result;
    }
}
